<?php

namespace app\lib;

use Firebase\JWT\JWT;
use app\lib\exception\TokenException;
use think\facade\Request;
use think\facade\Config;
class JwtHander
{
    /**
     * 类静态实例对象
     *
     * @var null
     */
    static private $_instance = null;
    /**
     * 获取单例
     *
     * @return null|JwtHander
     */
    static function getInstance()
    {
        if (!self::$_instance instanceof self) {
            self::$_instance = new self;
        }
        return self::$_instance;
    }
    /**
     * 构造方法
     *
     * JwtHander constructor.
     */
    private function __construct()
    {
    }
    /**
     * 生成jwt
     * @param $id
     * @param $host
     * @return string
     */
    public function generateJwt($id, $host)
    {

        $key = Config::get('jwt.key');
        $time = time();

        //公用信息
        $token = [
            'iss' => $host,
            'iat' => $time,
            'sub' => $id
        ];

        $access_token = $token;
        $access_token['exp'] = $time+Config::get('jwt.expire');

        return [
            'token' => JWT::encode($access_token,$key),
            'token_type' => 'Bearer'
        ];


    }
    /**
     * 解密jwt
     *
     * @param $header
     * @return bool
     */
    public function decodeJwt()
    {

        $header = Request::header();
        if (!empty($header['authorization'])) {
            $key = Config::get('jwt.key');

            $token = str_replace('Bearer ', '', $header['authorization']);
            
            try {
                $jwtInfo = (array)JWT::decode($token, $key, array('HS256'));
            } catch (\Exception $e) {
                throw new TokenException();
            }

            return $jwtInfo;


        } else {
            throw new TokenException();
        }
    }
}